import Widget from './Widget'

/** 尺寸范围 */
export function getSizeRange(widget: Widget) {
  const { option, aspectRatio: ratio, page, isRiding, isBatch } = widget

  let { w, h } = page

  // 骑缝控件或批量章取最小页面尺寸
  if (isRiding || isBatch) {
    const { minWidth, minHeight } = widget.pageRange
    w = minWidth
    h = minHeight
  }

  let { minWidth: minW = 0, minHeight: minH = 0, maxWidth: maxW = Infinity, maxHeight: maxH = Infinity } = option

  minW = Math.max(0, minW)
  minH = Math.max(0, minH)
  maxW = Math.min(maxW, w)
  maxH = Math.min(maxH, h)

  if (ratio) {
    const ratioMinWidth = minH * ratio
    const ratioMinHeight = minW / ratio
    const ratioMaxWidth = maxH * ratio
    const ratioMaxHeight = maxW / ratio

    minW = Math.max(minW, ratioMinWidth)
    minH = Math.max(minH, ratioMinHeight)
    maxW = Math.min(maxW, ratioMaxWidth)
    maxH = Math.min(maxH, ratioMaxHeight)
  }

  return {
    minW,
    maxW,
    minH,
    maxH
  }
}

/** 设置控件宽度 */
export function setWidth(widget: Widget, w: number, adjust = true) {
  const ratio = widget.aspectRatio

  w = w ?? widget.sizeRange.minW

  const h = ratio ? w / ratio : widget.h

  Object.assign(widget, { w, h })

  adjust && widget.adjust()
}

/** 设置控件高度 */
export function setHeight(widget: Widget, h: number, adjust = true) {
  const ratio = widget.aspectRatio

  h = h ?? widget.sizeRange.minH

  const w = ratio ? h * ratio : widget.w

  Object.assign(widget, { w, h })

  adjust && widget.adjust()
}

/** 适应控件尺寸以免超出边界 */
export function adjustSize(widget: Widget) {
  const { minW, maxW, minH, maxH } = widget.sizeRange
  let { w, h, aspectRatio: ratio } = widget

  if (w > maxW) {
    w = maxW
  } else if (w < minW) {
    w = minW
  }

  if (h > maxH) {
    h = maxH
  } else if (h < minH) {
    h = minH
  }

  if (ratio) {
    h = Math.round(w / ratio)
  }

  Object.assign(widget, { w, h })
}
